import random

from django.core.paginator import Paginator
from django.utils import timezone
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.views.decorators.http import require_http_methods
from django.contrib.auth.hashers import make_password, check_password
from captcha.image import ImageCaptcha
# from appointment.models import AppointmentModel
from organization.models import OrganizationModel, NoticeModel
from student.models import StudentModel
from supervisor.models import JobPosting, InterviewSchedule, InternshipPosting

count_loging = 0


# Create organization views here.
class RegisterView(View):
    """ 企业注册 """

    def get(self, request):
        """ get请求提供企业注册界面 """
        return render(request, 'register/organization_register.html')

    def post(self, request):
        """ post请求实现企业注册业务逻辑 """
        # # 对密码加密
        encrypt_pwd = make_password(request.POST.get('password'))
        # 向数据库中添加一个企业
        OrganizationModel.objects.create(
            name=request.POST.get('org_name'),
            password=encrypt_pwd,  # 开启密码加密
            email=request.POST.get('email'),
            phone_number=request.POST.get('phone_number'),
            address=request.POST.get('address'),
            description=request.POST.get('description')
        )

        # 添加成功返回200
        result_data = {'code': 200}
        return JsonResponse(result_data)


# 验证企业的唯一性
@require_http_methods(['POST'])
def check_number(request):
    """ 验证用户是否唯一 """
    result_data = {}
    # {'valid': True} 如果返回的是Ture: 表示验证合法，通过
    # {'valid': False} 如果返回的是False: 表示验证非法，不通过

    org_name = request.POST.get('org_name')
    email = request.POST.get('email')

    # 验证组织名称或者组织账号是否已经注册过了
    check_name = OrganizationModel.objects.filter(name=org_name)
    check_email = OrganizationModel.objects.filter(email=email)

    if check_name or check_email:
        # 已经存在一个职工号相同的用户
        result_data['valid'] = False
        return JsonResponse(result_data)
    else:
        # 职工号不重复就返回真
        result_data['valid'] = True
        return JsonResponse(result_data)


class LoginView(View):
    """ 企业登录 """

    def get(self, request):
        """ get请求提供企业登录界面 """
        return render(request, 'login/organization_login.html')

    def post(self, request):
        """ post请求实现企业登录业务逻辑 """
        global count_loging
        try:
            if not request.COOKIES.get('user_locked'):  # 如果没有被封，才进行判断登录次数
                if count_loging < 4:  # 判断登录次数
                    count_loging += 1  # 每登录一次，次数加一
                    email = request.POST.get('email')    # 得到组织账号
                    password = request.POST.get('password')  # 得到原始密码
                    organization = OrganizationModel.objects.get(email=email)
                    encrypt_pwd = organization.password  # 根据账号找到相应的组织，并比较密码

                    if check_password(password, encrypt_pwd):  # 当密码正确时写入cookie
                        # 检测是否通过管理员审核
                        if not organization.check:
                            return JsonResponse({'code': 403})  # 审核中
                        # 返回200状态码，前端JS会自动跳转到首页
                        result_data = {'code': 200}
                        response = JsonResponse(result_data)
                        # 登录成功在cookie中写入is_login已登录标志
                        response.set_cookie("user_status", "is_login")
                        # 并且创建一个session，将tch_num装进去
                        request.session['user_id'] = email
                        return response  # 返回响应
                    else:
                        result_data = {'code': 401}  # 当密码错误的时候返回状态码401表示登录失败
                        return JsonResponse(result_data)
                else:
                    # 登录尝试超过5次，就会设置一个cookie记录封禁的时长
                    result_data = {'code': 402}  # 402错误标识为输入次数过多
                    response = JsonResponse(result_data)
                    response.set_cookie("user_locked", "True", max_age=60 * 5)  # 这里max_age=封多久，60*5代表5分钟
                    count_loging = 0
                    return response
            else:
                result_data = {'code': 402}  # 402错误标识为输入次数过多
                response = JsonResponse(result_data)
                return response
        except:
            result_data = {'code': 401}
            return JsonResponse(result_data)


# 组织的home
def home(request):
    # 获取当前登录用户的id
    email = request.session.get('user_id')
    # 通过id找到当前登录用户
    organization = OrganizationModel.objects.filter(email=email)
    student = StudentModel.objects.filter(stu_num=email)
    if organization.exists():
        user_label = 2
        organization = organization[0]
    elif student.exists():
        user_label = 1
        student = student[0]
    else:
        user_label = 3

    # 将数据渲染到前端HTML模版里
    return render(request, 'home_page/organization_index.html', locals())


# 生成验证码
@require_http_methods(['GET'])
def generate_code(request):
    # 生成随机的4位数字与字母组合的验证码
    captcha_str = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 4))
    # 生成验证码图片
    image = ImageCaptcha().generate_image(captcha_str)
    # 将验证码存入session，方便后续验证
    request.session['verify_code'] = captcha_str
    # 将验证码图片以PNG格式返回给前端
    response = HttpResponse(content_type='image/png')
    image.save(response, 'PNG')
    return response


# 校验验证码
@require_http_methods(['POST'])
def verify_code(request):
    """验证: 验证码是否正确"""
    # {'valid': True} 如果返回的是Ture: 表示验证合法，通过
    # {'valid': False} 如果返回的是False: 表示验证非法，不通过
    result_data = {'valid': True}  # 先定义一个默认的返回参数
    code1 = request.POST.get('captcha')  # 接受请求参数
    # 服务器里面在前一次请求的时候就已经存了验证码：
    code2 = request.session['verify_code']
    if not code1.lower() == code2.lower():
        # 客户端的验证码写错了
        result_data['valid'] = False
    return JsonResponse(result_data)


# 发布招聘信息
class CreateJobView(View):

    def get(self, request):
        # 获取当前登录用户的id
        email = request.session.get('user_id')
        # 通过id找到当前登录用户
        organization = OrganizationModel.objects.filter(email=email)
        student = StudentModel.objects.filter(stu_num=email)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
        return render(request, 'job_posting/post-jobs.html', locals())

    def post(self, request):

        try:
            title = request.POST.get('title')
            description = request.POST.get('description')
            requirements = request.POST.get('requirements')
            salary_range = request.POST.get('salary_range')
            location = request.POST.get('location')
            deadline = request.POST.get('deadline')
            organization = OrganizationModel.objects.filter(email=request.session.get('user_id'))[0]

            # 企业发布一条就业岗位信息
            JobPosting.objects.create(
                title=title,
                description=description,
                requirements=requirements,
                salary_range=salary_range,
                location=location,
                organization=organization,
                deadline=deadline
            )
            # 发布一条公告给所有关注了该企业的学生
            NoticeModel.objects.create(
                title='发布了新的岗位！',
                content=title,
                publisher=organization,
            )
            result_data = {'code': 200}
            return JsonResponse(result_data)
        except Exception as e:
            print(e)
            result_data = {'code': 500}
            return JsonResponse(result_data)


# 展示就业招牌岗位信息
class ShowJobView(View):

    def get(self, request):
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 通过id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
            # 找到organization发布的所有招聘信息
            job_postings = JobPosting.objects.filter(organization=organization)

        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3

        return render(request, 'job_posting/show-jobs.html', locals())


class JobDetailView(View):

    def get(self, request):
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 获取当前点击的岗位id
        job_id = request.GET.get('job_id')
        # 根据user_id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3

        # 根据job_id找到当前点击的岗位
        job = JobPosting.objects.filter(id=job_id)[0]
        # 根据job_posting.organization_id找到当前岗位的所属企业
        org = OrganizationModel.objects.filter(id=job.organization_id)[0]

        return render(request, 'job_posting/job-detail.html', locals())


class ManageInterviewView(View):

    def get(self, request):
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 通过id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
            # 找到organization有关的所有面试预约
            all_interview_schedules = InterviewSchedule.objects.filter(organization=organization)
            paginator = Paginator(all_interview_schedules, 5)  # 每页显示5条数据
            page_number = request.GET.get('page')
            interview_schedules = paginator.get_page(page_number)

        elif student.exists():
            user_label = 1
            student = student[0]
            # 学生用户不需要分页显示面试预约
        else:
            user_label = 3
            # 管理员用户不需要分页显示面试预约

        return render(request, 'interview/show-interview.html', locals())


class InterviewDetailView(View):

    def get(self, request):
        # 当前查询的是哪一个面试预约
        interview_id = request.GET.get('interview_id')
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 通过id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
            # 根据interview_id找到当前点击的岗位
            interview = InterviewSchedule.objects.filter(id=interview_id)
            if interview.exists():
                interview = interview[0]

        elif student.exists():
            user_label = 1
            student = student[0]
            # 学生用户不需要分页显示面试预约
        else:
            user_label = 3
            # 管理员用户不需要分页显示面试预约

        return render(request, 'interview/interview-detail.html', locals())


    def post(self, request):
        try:
            # 获取当前登录用户的id
            user_id = request.session.get('user_id')
            # 通过id找到当前登录用户
            # 用户可能是学生1，企业2，管理员3，用if语句来判断
            organization = OrganizationModel.objects.filter(email=user_id)
            student = StudentModel.objects.filter(stu_num=user_id)

            interview_mode = request.POST.get('mode')
            status = request.POST.get('status')
            location = request.POST.get('location')
            interview_id = request.POST.get('interview_id')
            print(interview_mode, status, location, interview_id)

            # 修改面试预约表的信息
            if interview_mode:
                InterviewSchedule.objects.filter(id=interview_id).update(interview_mode=interview_mode)
            if status:
                InterviewSchedule.objects.filter(id=interview_id).update(status=status)
            if location:
                InterviewSchedule.objects.filter(id=interview_id).update(location=location)

            return JsonResponse({'code': 200})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500})


class ShowInternshipView(View):
    def get(self, request):
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 通过id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
            # 找到organization有关并且状态是已确认的所有面试预约
            all_interview_schedules = InterviewSchedule.objects.filter(organization=organization, status='confirmed')
            paginator = Paginator(all_interview_schedules, 5)  # 每页显示5条数据
            page_number = request.GET.get('page')
            interview_schedules = paginator.get_page(page_number)

        elif student.exists():
            user_label = 1
            student = student[0]
            # 学生用户不需要分页显示面试预约
        else:
            user_label = 3
            # 管理员用户不需要分页显示面试预约
        return render(request, 'internship/list-internship.html', locals())


class PostInternshipView(View):
    def get(self, request):
        # 当前查询的是哪一个面试预约
        interview_id = request.GET.get('interview_id')
        # 获取当前登录用户的id
        user_id = request.session.get('user_id')
        # 通过id找到当前登录用户
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
            # 根据interview_id找到当前点击的岗位
            interview = InterviewSchedule.objects.filter(id=interview_id)
            if interview.exists():
                interview = interview[0]

        elif student.exists():
            user_label = 1
            student = student[0]
            # 学生用户不需要分页显示面试预约
        else:
            user_label = 3
            # 管理员用户不需要分页显示面试预约
        return render(request, 'internship/post-internship.html', locals())

    def post(self, request):

        try:
            # post请求表单中获得description、requirements、duration、location、start_date、end_date、organization_id、student_id
            InternshipPosting.objects.create(
                title=request.POST.get('title'),
                description=request.POST.get('description'),
                requirements=request.POST.get('requirements'),
                duration=request.POST.get('duration'),
                location=request.POST.get('location'),
                start_date=request.POST.get('start_date'),
                end_date=request.POST.get('end_date'),
                organization_id=request.POST.get('organization_id'),
                student_id=request.POST.get('student_id'),
            )
            result_data = {'code': 200}
            return JsonResponse(result_data)
        except Exception as e:
            print(e)
            result_data = {'code': 500}
            return JsonResponse(result_data)



